package com.itluma.openapi.apimapping.controller;

import com.github.pagehelper.PageInfo;
import com.itluma.openapi.apimapping.service.ApiMappingService;
import com.itluma.openapi.bean.AjaxMessage;
import com.itluma.openapi.bean.LayUITable;
import com.itluma.openapi.exception.ExceptionEnum;
import com.itluma.openapi.exception.OpenApiException;
import com.itluma.openapi.pojo.ApiMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;


@RestController
@RequestMapping("/apimapping")
public class ApiMappingController {
    @Autowired
    private ApiMappingService apiMappingService;

    @GetMapping("/table")
    public LayUITable<ApiMapping> table(ApiMapping apiMapping, @RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        PageInfo<ApiMapping> table = apiMappingService.table(apiMapping, page, limit);
        LayUITable<ApiMapping> layUITable = new LayUITable<ApiMapping>();
        if (table != null && table.getList().size() > 0) {
            layUITable.setCode(0);
            layUITable.setCount((int) table.getTotal());
            layUITable.setData(table.getList());
        } else {
            layUITable.setCode(1000);
            layUITable.setMsg("查询失败！");
        }
        return layUITable;
    }

    @PostMapping("/add")
    public AjaxMessage add(@RequestBody ApiMapping apiMapping) {
        ApiMapping retApiMapping = apiMappingService.add(apiMapping);
        AjaxMessage ajaxMessage  = new AjaxMessage();
        if (retApiMapping != null) {
            ajaxMessage.setCode(0);
        }else{
            ajaxMessage.setCode(100);
            ajaxMessage.setMessage("路由添加失败");
        }

        return ajaxMessage;
    }

    @PutMapping("/edit")
    public AjaxMessage edit(@RequestBody ApiMapping apiMapping) {
        ApiMapping retApiMapping = apiMappingService.edit(apiMapping);
        //ApiMapping retApiMapping = null;
        AjaxMessage ajaxMessage  = new AjaxMessage();
        if (retApiMapping != null) {
            ajaxMessage.setCode(0);
        }else{
            throw new OpenApiException(ExceptionEnum.APIMAPPING_EDIT_ERROR);
        }
        return ajaxMessage;
    }

    @DeleteMapping("/delete")
    public AjaxMessage delete(@RequestBody Integer[] id) {
        Boolean result = apiMappingService.delete(id);
        AjaxMessage ajaxMessage  = new AjaxMessage();
        if (result) {
            ajaxMessage.setCode(0);
        }else{
            throw new OpenApiException(ExceptionEnum.APIMAPPING_EDIT_ERROR);
        }
        return ajaxMessage;
    }
}
